<script setup lang="ts">
import { changeUserPass } from '../../api/user'
import { useUserStore } from '../../store/userStore'
import { useTokenStore } from '../../store/tokenStore'
import { useCrumbStore } from '../../store/crumbStore'
import { useRouter } from "vue-router";
import { ref } from "vue"
import { removeToken, removeUser } from "../../utils/session";
import { ElMessage } from "element-plus";
import { HttpStatusCode } from "axios";
import { storeToRefs } from 'pinia'

let old_pass = ref('')
let new_pass = ref('')
const crumbStore = useCrumbStore()
const userStore = useUserStore()
const tokenStore = useTokenStore()
const router = useRouter()
const { user } = storeToRefs(userStore)

const sub = async () => {
  let mUser = user.value as User
  let data = {
    old_pass: old_pass.value,
    new_pass: new_pass.value
  }
  const res = await changeUserPass(mUser.id, data)
  if(res.statusCode === HttpStatusCode.Ok || res.statusCode === HttpStatusCode.Created) {
    ElMessage({
      type: 'success',
      message: '修改成功，请重新登录'
    })
    await logout()
  } else {
    ElMessage({
      type: 'error',
      message: '修改失败，请重试'
    })
  }
}

const logout = async () => {
  tokenStore.delToken()
  userStore.delUser()
  removeToken()
  removeUser()
  crumbStore.clearCrumb()
  await router.push({path: '/login'})
}

</script>

<template>
  <div class="container">
    <span class="title">旧密码</span>
    <el-input class="inp" type="password" v-model="old_pass" placeholder="输入旧密码" show-password />
    <span class="title">新密码</span>
    <el-input class="inp" type="password" v-model="new_pass" placeholder="输入新密码" show-password />
    <el-button type="primary" class="btn" @click="sub">确认</el-button>
  </div>
</template>

<style scoped lang="less">
.container {
  width: 500px;
  height: 300px;
  margin: 20px;
  display: flex;
  flex-direction: column;
  .title {
    font-size: 18px;
    margin-bottom: 10px;
  }
  .inp {
    margin-bottom: 10px;
  }
  .btn {
    margin-top: 10px;
    width: 60px;
    height: 30px;
  }
}
</style>